<?php
/**
 * 验证码文件
 */
include_once(dirname(__file__).'/../../init.php');
define('CODE_WIDTH',         350);
define('CODE_HEIGHT',        120);
define('CODE_FONT_SIZE',     15);
define('CODE_CHARS_COUNT',   4);
define('CODE_LINES_COUNT',   10);
define('CODE_CHAR_COLORS',   "#880000,#008800,#000088,#888800,#880088,#008888,#000000");
define('CODE_LINE_COLORS',   "#DD6666,#66DD66,#6666DD,#DDDD66,#DD66DD,#66DDDD,#666666");
define('CODE_BG_COLOR',      "#FFFFFF");
define('CODE_ALLOWED_CHARS', "ABCDEFGHJKLMNPQRTUVWXYZ2345689");
define('PATH_TTF',           "fonts");

$line_colors = explode(',',CODE_LINE_COLORS);
$char_colors = explode(',',CODE_CHAR_COLORS);
$fonts = collect_files(PATH_TTF, "ttf");

$img = imagecreatetruecolor(CODE_WIDTH, CODE_HEIGHT);
imagefilledrectangle($img, 0, 0, CODE_WIDTH - 1, CODE_HEIGHT - 1, gd_color(CODE_BG_COLOR));

//$fonts = imageloadfont($fonts);

// Draw lines

for ($i = 0; $i < CODE_LINES_COUNT; $i++){
	imageline($img,
			rand(0, CODE_WIDTH - 1),
			rand(0, CODE_HEIGHT - 1),
			rand(0, CODE_WIDTH - 1),
			rand(0, CODE_HEIGHT - 1),
			gd_color($line_colors[rand(0, count($line_colors) - 1)])
			);
	imagearc($img, rand(0,300), rand(0,300), rand(0,300), rand(0,300), 0, 360, gd_color($line_colors[rand(0, count($line_colors) - 1)]));

}
// Draw word bg
$bgword=array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","1","2","3","4","5","6","7","8","9","0");
for ($i = 0; $i < 20; $i++){
	$bg=rand(0,36);
	$bg1=rand(0,CODE_WIDTH);
	$bg2=rand(0,CODE_HEIGHT);
	imagechar($img,rand(1,10),$bg1,$bg2,$bgword[$bg],gd_color($char_colors[rand(0, count($char_colors) - 1)]));
}

// Draw code

$code = "";
$y = (CODE_HEIGHT / 1.6) + (CODE_FONT_SIZE / 1.6);
for ($i = 0; $i < CODE_CHARS_COUNT; $i++) {
	$color = gd_color($char_colors[rand(0, count($char_colors) - 1)]);
	$angle = rand(-30, 30);
	$char = substr(CODE_ALLOWED_CHARS, rand(0, strlen(CODE_ALLOWED_CHARS) - 1), 1);
	$font = PATH_TTF . "/" . $fonts[rand(0, count($fonts) - 1)];
	$x = (intval((CODE_WIDTH / CODE_CHARS_COUNT) * $i) + (CODE_FONT_SIZE / 2));
	$code .= $char;
	imagettftext($img, rand(40,50), $angle, $x, $y, $color, $font, $char);
}

$_SESSION['picNum'] = strtolower($code);

header("Content-Type: image/gif");
imagegif($img);
imagedestroy($img);


function gd_color($html_color) {
	return preg_match('/^#?([\dA-F]{6})$/i', $html_color, $rgb) ? hexdec($rgb[1]) : false;
}


function collect_files($dir, $ext) {
	if (false !== ($dir = opendir($dir))) {
		$files = array();

		while (false !== ($file = readdir($dir)))
		if (preg_match("/\\.$ext\$/i", $file))
			$files[] = $file;

		return $files;

	} else
		return false;
}

?>